
import os
from flask import Blueprint, jsonify,request
from flask_cors import CORS
import json
from service.backtestService import BacktestService
import time

backtest_controller = Blueprint('backtest_controller', __name__)
CORS(backtest_controller)
@backtest_controller.route('/get_item_list_by_description',methods=['POST'])
def getItemListByDescription():
    request_json = request.json
    sorted_item_list = BacktestService().getItemListByDescription(request_json["scenario_id"],request_json["description"])
    return json.dumps([ob for ob in sorted_item_list])

@backtest_controller.route('/start_backtest',methods=['POST'])
def startBacktest():
    request_json = request.json
    backtest_form = request_json['backtest_form']
    backtestService = BacktestService()
    if backtest_form['backtest_type']=='stock':
        report = backtestService.initStockBacktest(backtest_form['scenario_id'],backtest_form['start_date'],backtest_form['end_date'],backtest_form['stock_id'],backtest_form['cash'],backtest_form['indicator_type'],backtest_form['custom_indicator_list'],backtest_form['strategy_description_list'],backtest_form['item_uuid'],backtest_form['compare_stock_id'])
    elif backtest_form['backtest_type']=='portfolio':
        report = backtestService.initPortfolioBacktest(backtest_form['scenario_id'],backtest_form['start_date'],backtest_form['end_date'],backtest_form['cash'],backtest_form['indicator_type'],backtest_form['custom_indicator_list'],backtest_form['init_investment'],backtest_form['strategy_description_list'],backtest_form['compare_stock_id'])
    report['date_list'] = [int(time.mktime(dt.timetuple())) for dt in report['date_list']]
    for item in report['item_list']:
        item['start_date'] = int(time.mktime(item['start_date'].timetuple()))
        item['end_date'] = int(time.mktime(item['end_date'].timetuple()))
  
    return json.dumps(report)